package com.clouds.wms.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 公用静方�? * @author liuchen
 */
public class Function {
	/**
	 * 返回字符串,指定格式的当前日期
	 * 
	 * @return
	 */
	public static String getNow() {
		return getDateString(new Date());
	}
	/**
	 * 获得某一天的后几天的时间
	 */
	public static Date getDateAfters(Date endDate, int days) {
		Calendar c = Calendar.getInstance();
		c.setTime(endDate);
		c.add(Calendar.DATE, days);
		Date startDate = c.getTime();
		return startDate;
	}

	/**
	 * 返回当前日期的字符串 格式为YYYY-MM-DD
	 * 
	 * @return
	 */
	public static String getDateString(java.util.Date date) {
		if (date == null)
			return "";
		java.sql.Timestamp ts = new Timestamp(date.getTime());
		String str = getDateTimeString(ts);
		if (str.length() >= 10) {
			str = str.substring(0, 10);
		}
		return str;
	}

	/**
	 * 取得给定时间的字符串表示
	 * @param ts java.sql.Timestamp
	 * @return String 格式003-03-03 19:01:00
	 */
	public static String getDateTimeString(java.sql.Timestamp ts) {
		if (ts == null)
			return "";
		String str = ts.toString();
		if (str.length() >= 19) {
			str = str.substring(0, 19);
		}
		return str;
	}
	
	/**
	 * 将当前日期转换为指定格式的字符串
	 * @param pattern 格式
	 * @return String
	 */
	public static String getDateStringByPattern(String pattern) {
		Date date = new Date();
		return getDateStringByPattern(date, pattern);
	}

	/**
	 * 判断字符串是否包含汉
	 * @param str
	 * @return
	 */
	public static boolean  isIncludeChineseChar(String str){
		if(str.length() == str.getBytes().length){
			return false;
		}else{
			return true;
		}
	}
	
	/**
	 * 判断字符串既包含字符串又包含字母
	 * @param str
	 * @return
	 */
	public static boolean  isChEnChar(String str){
		boolean  isCh = false;
		boolean  isEn = false;
		for(int i = 0 ; i < str.length() ; i++ ){
	        String splitStr = str.substring(i,i+1);
			if(splitStr.getBytes().length ==1){
				isEn = true;
			    continue;
			}
			// 不同的系统环境下汉字的splitStr.getBytes().length 值不�?��
			//GBK 2 ,UTF-8 3
			if(splitStr.getBytes().length > 1){
				isCh = true;
			    continue;
			}
		}
		if(isCh && isEn){
			return true;
		}
		return false;
	}
	
	/**
	 * 将指定日期转换为指定格式的字符串
	 * @param date (java.util.Date )
	 * @param pattern 日期格式，如yyyy-MM-dd" yyyy-MM-dd HH:mm:ss HH:mm:ss"
	 * @return String
	 */
	public static String getDateStringByPattern(Date date, String pattern) {
		if(date == null) {
			return "";
		}
		SimpleDateFormat sf = new SimpleDateFormat(pattern);
		String str = sf.format(date);
		return str;
	}

	/**
	 * 判断字符串是否为空，如果为空则返�?"
	 * @param s
	 * @return
	 */
	public static String isNull(String s) {
		if (s != null && !"".equals(s) && !"null".equals(s)) {
			return s;
		} else {
			return "";
		}
	}
	
	/**
	 * 获取参数值，如果没有则返回默�?
	 * @param request
	 * @param paraName
	 * @param defaultValue
	 * @return
	 */
	public static String getParam(HttpServletRequest request, String paraName, String defaultValue) {
		String rs = request.getParameter(paraName);
		if (rs == null || "".equals(rs.trim())) {
			return defaultValue;
		} else {
			return rs;
		}
	}
	
	/**
	 * 替换XML中特殊字
	 * @param request
	 * @param paraName
	 * @return
	 */
	public static String escape(String s) {
        if (s == null)
            return "";
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if ((int) ch < 32) {
                continue;
            }
            if (ch == '<') {
                sb.append("&lt;");
            } else if (ch == '>') {
                sb.append("&gt;");
            } else if (ch == '\'') {
                sb.append("&apos;");
            } else if (ch == '"') {
                sb.append("&quot;");
            } else if (ch == '&' && 
        		s.indexOf("&amp;", i) != i && 
        		s.indexOf("&lt;", i) != i && 
        		s.indexOf("&gt;", i) != i && 
        		s.indexOf("&quot;", i) != i && 
        		s.indexOf("&apos;", i) != i &&
        		s.indexOf("&#", i) != i) {
                sb.append("&amp;");
            } else {
                sb.append(ch);
            }
        }
        return sb.toString();
    }

	/**
	 * 发HTTP请求
	 * @param urlString
	 * @param urlParams
	 * @return
	 * @throws Exception
	 */
	public static String sendByUrlReal(String urlString, String urlParams) throws Exception {
		String info = "";
		String response = null;
        BufferedReader in = null;
        try {
            URL url = new URL(urlString);
            URLConnection urlConn = url.openConnection();
            if (urlParams != null && urlParams.length() > 0) {
	            urlConn.setDoOutput(true);
	            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(urlConn.getOutputStream()));
	            out.write(urlParams);
	            out.close();
            }
            in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String line = null;
            StringBuffer buffer = new StringBuffer(4096);
            while ((line = in.readLine()) != null) buffer.append(line + "\n");
            response = buffer.toString();
        } catch (Exception e) {
            info += "|"+e;
            throw e;
        } finally {
            if (in != null) try { in.close(); } catch(Exception e) {}
            info += "|"+response;
        }
        return info;
	}
	
	/**
	 * 将一个字符串转为合法的sql语句要求的表示方法�?主要是对单引号的处理
	 * @param str
	 * @return 处理后的字符
	 */
	public static String formatSQLString(String str) {
		if(str == null) {
			return null;
		}
		return str.replace("'", "''");
	}
	
	public static boolean isMobile(String mobile) {
		String regExp = "^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(mobile);
		return m.find();
	}
	
	/**
	 * 获得小写字母和数字的组合字符
	 * @param length
	 * @return
	 */
	public static String getCharAndNumr(int length) {
		String val = "";     
	    Random random = new Random();     
	    for(int i = 0; i < length; i++) {     
	        String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字
	        if("char".equalsIgnoreCase(charOrNum)) {// 字符�?
	            int choice = 97;//random.nextInt(2) % 2 == 0 ? 65 : 97; //取得大写字母还是小写字母
	            val += (char) (choice + random.nextInt(26));
	        } else if("num".equalsIgnoreCase(charOrNum)) { // 数字
	            val += String.valueOf(random.nextInt(10));
	        }
	    }
	    return val;
	}
	

	/**
	 * 根据时间段，返回给定格式的日期list<String>
	 * @param startDate
	 * @param endDate
	 * @param format
	 * @return
	 */
	public static List<String> getDateList(Date startDate, Date endDate,
			String format) {
		try {
			List<String> list = new ArrayList<String>();
			Calendar cal = Calendar.getInstance();
			cal.setTime(startDate);
			Calendar calend = Calendar.getInstance();
			calend.setTime(endDate);
			while (cal.before(calend)) {
				list.add(getDateStringByPattern(cal.getTime(), format));
				cal.add(Calendar.DATE, 1);
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 判断是否数字
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(String str){
	   Pattern pattern = Pattern.compile("[0-9]*");
	   Matcher isNum = pattern.matcher(str);
	   if(!isNum.matches()){
	       return false;
	   }
	   return true;
	}

	/**
	 * 替换html代码中特殊字
	 * @param str
	 * @return
	 */
	public static String htmlSpecialChars(String str) {
		str = str.replaceAll("&", "&amp;");
		str = str.replaceAll("<", "&lt;");
		str = str.replaceAll(">", "&gt;");
		str = str.replaceAll("\"", "&quot;");
		return str;
	}

	/**
	 * 替换换行
	 * @param str
	 * @return
	 */
	public static String replaceEnter(String str) {
		return str == null ? "" : str.replace("\r\n", "<br/>");
	}

	/**
	 * 转换字符串编
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String transform(String str) {
		String s = null;
		try {
			if (str == null)
				return "";
			if ("".trim().equals(str))
				return "";
			byte[] b = str.getBytes("ISO-8859-1");
			s = new String(b, "UTF-8");

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return s;
	}

	/**
	 * 判断是否是EMAIL
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) { 
	     boolean tag = true; 
	     final String pattern1 = "^([a-z0-9A-Z]+[-_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; 
	     final Pattern pattern = Pattern.compile(pattern1); 
	     final Matcher mat = pattern.matcher(email); 
	     if(!mat.find()) { 
	         tag = false; 
	     } 
	     return tag; 
	 }
	
	/**
	 * 判断是否是电话号码，包括手机和座�?
	 * @param email
	 * @return
	 */
	public static boolean isPhoneNo(String phoneNo) { 
	     boolean tag = true; 
	     final String pattern1 = "(^[0-9]{3,4}\\-[0-9]{7,8}$)|(^[0-9]{7,8}$)|(^\\([0-9]{3,4}\\)[0-9]{3,8}$)|(^0{0,1}1[0-9]{10}$)"; 
	     final Pattern pattern = Pattern.compile(pattern1); 
	     final Matcher mat = pattern.matcher(phoneNo); 
	     if(!mat.find()) { 
	         tag = false; 
	     } 
	     return tag; 
	}

	/**
	 * 判断是否是数字和字母组合
	 * @param str
	 * @return
	 */
	public static boolean isLetterAndNumber(String str) { 
	     boolean tag = true; 
	     final String pattern1 = "^[A-Za-z0-9]+$"; 
	     final Pattern pattern = Pattern.compile(pattern1); 
	     final Matcher mat = pattern.matcher(str); 
	     if(!mat.find()) { 
	         tag = false; 
	     } 
	     return tag; 
	 }
	
	/**
	 * 创建目录
	 * @param url
	 * @throws IOException
	 */
	public static void mkdir(String url) throws IOException {
		String path = "";
		if (url.indexOf("/") != -1) {
			if (url.endsWith("/")) {
				path = url.substring(0, url.lastIndexOf("/"));
			} else {
				path = url;
			}
		} else if (url.indexOf("\\") != -1) {
			if (url.endsWith("\\")) {
				path = url.substring(0, url.lastIndexOf("\\"));
			} else {
				path = url;
			}
		}
		path = path.length() != 0 ? path : "/";
		java.io.File physicalPath = new java.io.File(path);
		if (!physicalPath.exists()) {
			physicalPath.mkdirs();
		}
	}

	/**
	 * 产生随机等介于min,max)
	 * @param min
	 * @param max
	 * @return
	 */
    public static int rand(int min, int max) {
        Random random = new Random();
        return Math.abs(random.nextInt()) % ((max - min) + 1) + min;
    }

    /**
     * 获得星期�?
     * @return
     */
    public static String getDayOfWeek() {
    	Calendar c = Calendar.getInstance();
		int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
		String week = "";
		if(dayOfWeek == 2) {
			week = "week1";
		} else if(dayOfWeek == 3) {
			week = "week2";
		} else if(dayOfWeek == 4) {
			week = "week3";
		} else if(dayOfWeek == 5) {
			week = "week4";
		} else if(dayOfWeek == 6) {
			week = "week5";
		} else if(dayOfWeek == 7) {
			week = "week6";
		} else {
			week = "week7";
		}
		return week;
    }

	/**
	 * 判断是否是日�?
	 * @param email
	 * @return
	 */
	public static boolean isDate(String date) {
	     boolean tag = true;
	     final String pattern1 = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
	     final Pattern pattern = Pattern.compile(pattern1);
	     final Matcher mat = pattern.matcher(date);
	     if(!mat.find()) {
	         tag = false;
	     }
	     return tag;
	}
	
	public static String getMACAddress() throws UnknownHostException, SocketException {
		InetAddress ia = InetAddress.getLocalHost();
		//获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中�?
		byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
		//下面代码是把mac地址拼装成String
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<mac.length;i++){
			if(i!=0){
				sb.append("-");
			}
			//mac[i] & 0xFF 是为了把byte转化为正整数
			String s = Integer.toHexString(mac[i] & 0xFF);
			sb.append(s.length()==1?0+s:s);
		}
		//把字符串�?��小写字母改为大写成为正规的mac地址并返�?
		return sb.toString().toUpperCase();
	}
	/**
	 * 判断何时在sql语句中添加"where"或"and"
	 * 
	 * @author dzhen.wang
	 * @param sql 
	 * @param hasWhere
	 * @return
	 */
	public static boolean appendWhereIfNeed(StringBuffer sql, boolean hasWhere) {
		if (hasWhere == false)
			sql.append(" WHERE ");
		 else 
			sql.append(" AND ");
		return true;
	}
	/**
	 * 批量操作时候把传进的参数转成SQL直接可用参数
	 * 例：a,b,c 转成 'a','b','c'
	 * @author dzhen.wang
	 * @param str  
	 * @return string
	 */
	public static String str2sql(String str) {
		String[] paras = str.split(",");
		StringBuffer sb = new StringBuffer();
		for(String para : paras){
			sb.append("'").append(para).append("'").append(",");
		}
		sb.delete(sb.length()-1, sb.length());
		return sb.toString();
	}
	/**
	 * 计算带税前金额
	 * @param taxType 税种
	 * @param taxRate 税率
	 * @param price 单价
	 * @param qty 计价数量
	 * @return
	 */
	public static double amount(int taxType,double taxRate,double price, double qty){
		double amount = 0.00;
		if(taxType == 1){
			amount = price/(1+(taxRate/100))*qty;
		}else{
			amount = price*qty;
		}
		return Math.floor(amount*100+.5)/100;
	}
	/**
	 * 把float转换为两位小数的
	 * @param f
	 * @return
	 */
	public static float parseFloat(float f) {
		DecimalFormat df = new DecimalFormat("#.00");
		float result = Float.parseFloat(df.format(f));
		return result;
	}
	/**
	 * 计算税额
	 * @param taxType 税种
	 * @param taxRate 税率
	 * @param price 单价
	 * @param qty 计价数量
	 * @return
	 */
	public static double taxAmount(int taxType,double taxRate,double price,int qty){
		double taxAmount = 0.00;
		if(taxType == 1){
			taxAmount = (price/(1+(taxRate/100))*qty)*(taxRate/100);
		}
		return Math.floor(taxAmount*100+.5)/100;
	}
	public static  void main(String[] args) {
		System.out.println("2012-06-06".compareTo("2012-06-05"));
	}
	//求共有多少条记录
	public static String toCountSql(String sql){
		String reSql = "select count(*) ROWSUM from (" + sql + ") t";
		return reSql;
	}
	/**
	 * 使用前提是totalCount必须大于零
	 * @param sql
	 * @param pageNumber
	 * @param pageSize
	 * @param paraList
	 * @return
	 */		
	public static String mySqlQuery(String sql,int pageNumber,int pageSize,int totalCount) {
		int pageCount = 0;
		if (totalCount % pageSize == 0) {
			pageCount = totalCount / pageSize;
		} else {
			pageCount = totalCount / pageSize + 1;
		}
		if (pageNumber > pageCount) {
			pageNumber = pageCount;
		}
		if (pageNumber < 1) {
			pageNumber = 1;
		}
		int offset = (pageNumber - 1) * pageSize;
		return toMySqlPageSql(sql,offset,pageSize);	
	}
	//组装oracle分页语句
		public static String toMySqlPageSql(String sql,int offset,int pageSize){
			String reSql = "" ;
			reSql = sql
			+" limit " + offset + "," + pageSize;
			return reSql;
		}
		/**
		 * 向浏览器输出JSON字符串
		 * @param response
		 * @param outObj
		 * @throws IOException
		 */
		public static void toJson(HttpServletResponse response, Map<String,Object> map) throws IOException{
			response.setContentType("text/xml;charset=utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setDateHeader("Expires", 0);
			response.setHeader("Cache-Control", "no-cache");
			PrintWriter out  = response.getWriter();
			JSONObject datas = new JSONObject();
			datas.putAll(map);
			out.print(datas.toString());
		}
		/**
		 * 向浏览器输出JSON字符串
		 * @param response
		 * @param outObj
		 * @throws IOException
		 */
		public static void toJsonObject(HttpServletResponse response, Map<String,Object> map) throws IOException{
			response.setContentType("text;charset=utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setDateHeader("Expires", 0);
			response.setHeader("Cache-Control", "no-cache");
			PrintWriter out  = response.getWriter();
			JSONObject datas = new JSONObject();
			datas.putAll(map);
			out.print(datas.toString());
		}
		/**
		 * 向浏览器输出JSON字符串
		 * @param response
		 * @param outObj
		 * @throws IOException
		 */
		public static void toJsonObjectForFileUpload(HttpServletResponse response, Map<String,Object> map) throws IOException{
			response.setCharacterEncoding("gb2312");
			response.setHeader("Pragma", "No-cache");
			response.setDateHeader("Expires", 0);
			response.setHeader("Cache-Control", "no-cache");
			PrintWriter out  = response.getWriter();
			JSONObject datas = new JSONObject();
			datas.putAll(map);
			out.print(datas.toString());
		}
		/**
		 * 向浏览器输出JSON字符串
		 * @param response
		 * @param outObj
		 * @throws IOException
		 */
		public static String toJsonArray(HttpServletResponse response,List<Object> fcList) throws IOException{
			response.setContentType("text/xml;charset=utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setDateHeader("Expires", 0);
			response.setHeader("Cache-Control", "no-cache");
			PrintWriter out  = response.getWriter();
			JSONArray dataList = new JSONArray();
			dataList.addAll(fcList);
			out.print(dataList.toString());
			return null;
		}
}
